import axios from 'axios';
import OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';
import moment from 'moment';

const bashPath = '/sts';
const bucket = 'juguanghe';
const region = 'oss-cn-hangzhou';

const upload = async function (file: any) {
  let fileName = file.name;
  let sts = await axios.get(bashPath);
  const client = new OSS({
    region,
    accessKeyId: sts.data.AccessKeyId,
    accessKeySecret: sts.data.AccessKeySecret,
    stsToken: sts.data.SecurityToken,
    bucket,
    // 刷新临时访问凭证的时间间隔，单位为毫秒。
    refreshSTSTokenInterval: 3600 * 1000
  });
  let uuid = uuidv4() + fileName.substring(fileName.lastIndexOf('.'));

  return client
    .multipartUpload('tantao/' + uuid, file, {
      progress: (p, checkpoint) => {
        // console.log(p);
        // console.log(Math.floor(p * 100));
      },
      mime: file.type
    })
    .then((res: any) => {
      let url = res.res.requestUrls[0];
      if (url.indexOf('?') > -1) {
        // console.log('22222' + url.substring(0, url.indexOf('?')))
        console.log('22222' + url.substring(0, url.indexOf('?')).replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com'));
        return url.substring(0, url.indexOf('?')).replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
      } else {
        // console.log('当前时间' + moment().format('YYYYMMDD'));
        console.log('33333' + url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com'));
        return url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
      }
    })
    .catch((err) => {
      console.log('err', err);
    });
};

export default upload;
